package com.xk._03真题骗._02链表;

import com.xk._03真题骗._00bean.ListNode;

/*
 * @description: https://leetcode.cn/problems/add-two-numbers/
 * @author: xu
 * @date: 2022/10/27 20:01
 */
public class _2两数相加 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummyHead = new ListNode(0);
        ListNode lastNode = dummyHead;
        int carry = 0; // 进位值
        while (l1 != null || l2 != null) {
            int v1 = 0, v2 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }
            int sum = v1 + v2 + carry;
            // 设置进位值
            carry = sum / 10;
            // sum的个位数作为新节点的值
            lastNode.next = new ListNode(sum % 10);
            lastNode = lastNode.next;
        }
        if (carry == 1) {
            lastNode.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

}
